import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../../../common/models/index.dart';
import '../../../../../common/utils/toast_util.dart';
import '../../../../../common/api/activity_api.dart';
import '../../controller.dart';

/// 活动编辑页面
/// 提供活动信息的编辑功能，包括标题、描述、人数限制、费用方式等
class ActivityEditPage extends StatefulWidget {
  /// 要编辑的活动数据
  final ActivityData? activityData;
  
  const ActivityEditPage({
    super.key,
    this.activityData,
  });

  @override
  State<ActivityEditPage> createState() => _ActivityEditPageState();
}

class _ActivityEditPageState extends State<ActivityEditPage> {
  final _titleController = TextEditingController();
  final _descriptionController = TextEditingController();
  
  // 编辑状态
  bool _isLoading = false;
  
  // 获取控制器
  PlaysController get controller => Get.find<PlaysController>();

  @override
  void initState() {
    super.initState();
    _initializeData();
  }

  /// 初始化数据（回显）
  void _initializeData() {
    if (widget.activityData != null) {
      // 尝试从控制器中获取最新数据，如果没有则使用传入的数据
      ActivityData? latestActivity;
      try {
        final controller = Get.find<PlaysController>();
        // 从所有活动中查找对应的活动
        final targetId = widget.activityData!.activityId;
        for (final activity in controller.myActivities) {
          if (activity.activityId == targetId) {
            latestActivity = activity;
            break;
          }
        }
        
        // 如果在进行中的活动中没找到，尝试在已结束的活动中查找
        if (latestActivity == null) {
          for (final activity in controller.myEndedActivities) {
            if (activity.activityId == targetId) {
              latestActivity = activity;
              break;
            }
          }
        }
      } catch (e) {
        // 如果获取控制器失败，使用传入的数据
        print('获取最新活动数据失败: $e');
      }
      
      // 使用最新数据或传入数据
      final activity = latestActivity ?? widget.activityData!;
      
      // 回显活动标题
      _titleController.text = activity.activityTitle.isNotEmpty 
          ? activity.activityTitle 
          : '';
      
      // 回显活动详情
      _descriptionController.text = activity.activityDetails.isNotEmpty 
          ? activity.activityDetails 
          : '';
    }
  }

  @override
  void dispose() {
    _titleController.dispose();
    _descriptionController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFD94841),
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        title: const Text(
          '编辑活动',
          style: TextStyle(
            color: Colors.white,
            fontSize: 18,
            fontWeight: FontWeight.w600,
          ),
        ),
        centerTitle: true,
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 活动标题
            _buildTitleSection(),
            const SizedBox(height: 24),
            
            // 活动描述
            _buildDescriptionSection(),
            const SizedBox(height: 40),
            
            // 确定按钮
            _buildConfirmButton(),
          ],
        ),
      ),
    );
  }



  /// 构建活动标题区域
  Widget _buildTitleSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '活动标题',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w600,
            color: Colors.white,
          ),
        ),
        const SizedBox(height: 12),
        TextField(
          controller: _titleController,
          style: const TextStyle(color: Colors.black),
          decoration: InputDecoration(
            hintText: '请输入活动标题',
            hintStyle: TextStyle(color: Colors.grey.shade600),
            filled: true,
            fillColor: Colors.white,
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8),
              borderSide: BorderSide(color: Colors.grey.shade300),
            ),
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8),
              borderSide: BorderSide(color: Colors.grey.shade300),
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8),
              borderSide: const BorderSide(color: Colors.blue, width: 2),
            ),
            contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
          ),
        ),
      ],
    );
  }

  /// 构建活动描述区域
  Widget _buildDescriptionSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '活动描述',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w600,
            color: Colors.white,
          ),
        ),
        const SizedBox(height: 12),
        TextField(
          controller: _descriptionController,
          maxLines: 4,
          style: const TextStyle(color: Colors.black),
          decoration: InputDecoration(
            hintText: '请输入活动描述',
            hintStyle: TextStyle(color: Colors.grey.shade600),
            filled: true,
            fillColor: Colors.white,
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8),
              borderSide: BorderSide(color: Colors.grey.shade300),
            ),
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8),
              borderSide: BorderSide(color: Colors.grey.shade300),
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(8),
              borderSide: const BorderSide(color: Colors.blue, width: 2),
            ),
            contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
          ),
        ),
      ],
    );
  }

  /// 构建确定按钮
  Widget _buildConfirmButton() {
    return Container(
      width: double.infinity,
      height: 50,
      margin: const EdgeInsets.symmetric(horizontal: 0),
      child: ElevatedButton(
        onPressed: _isLoading ? null : _saveActivity,
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.white,
          foregroundColor: Colors.black,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(25),
          ),
          elevation: 2,
        ),
        child: _isLoading 
            ? Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  SizedBox(
                    width: 16,
                    height: 16,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      valueColor: AlwaysStoppedAnimation<Color>(Colors.black),
                    ),
                  ),
                  const SizedBox(width: 8),
                  const Text(
                    '保存中...',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ],
              )
            : const Text(
                '确定',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                ),
              ),
      ),
    );
  }






  /// 保存活动
  Future<void> _saveActivity() async {
    // 验证输入
    if (_titleController.text.trim().isEmpty) {
      ToastUtil.error('请输入活动标题');
      return;
    }
    
    if (_descriptionController.text.trim().isEmpty) {
      ToastUtil.error('请输入活动描述');
      return;
    }
    
    // 检查是否有要编辑的活动
    if (widget.activityData == null) {
      ToastUtil.error('未找到要编辑的活动信息');
      return;
    }

    setState(() {
      _isLoading = true;
    });

    try {
      // 调用API编辑活动（与MyApplication2一致，只传递activityId、activityTitle、activityDetails）
      final response = await ActivityApi.editActivity(
        activityId: widget.activityData!.activityId,
        activityTitle: _titleController.text.trim(),
        activityDetails: _descriptionController.text.trim(),
      );

      if (response.isSuccess) {
        ToastUtil.success(response.message.isNotEmpty ? response.message : '活动编辑成功');
        
        // 刷新控制器中的用户内容
        await controller.refreshUserContent();
        
        // 返回上一页，并传递true表示数据已更新
        Get.back(result: true);
      } else {
        ToastUtil.error('编辑失败: ${response.message}');
      }
    } catch (e) {
      ToastUtil.error('编辑失败: $e');
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

}